import { GlobalEvent } from "../base/GlobalEvent";
import { ConstData } from "../base/ConstData";
import { bindData, ifEnemyData, ifPlayerData, getData, ifWorldData } from "../Data/dataBase";
import { GlobalFunction } from "../base/GlobalFunction";

const {ccclass, property} = cc._decorator;

@ccclass
export default class worldMgr extends cc.Component {

    @property(cc.Node)
    mainCam:cc.Node = null;
    @property(cc.Node)
    player:cc.Node = null;
    @property(cc.Node)
    sword:cc.Node = null;
    @property(cc.Node)
    objectLayer:cc.Node = null;
    @property()
    isDebugDraw:boolean = false;

    isAttackMode:boolean = false;

    onLoad(){
        cc.director.getPhysicsManager().enabled = true;
        cc.director.getPhysicsManager().gravity = cc.v2(0, 0);
        cc.director.getPhysicsManager().debugDrawFlags = this.isDebugDraw ? 1 : 0;
        cc.director.getCollisionManager().enabledDebugDraw = this.isDebugDraw;

        bindData("WORLD_DATA", "ADD_ENEMY", this.addEnemy.bind(this), this);
        bindData("WORLD_DATA", "ADD_PLAYER", this.addPlayer.bind(this), this);

        var worldData:ifWorldData = getData("WORLD_DATA");
        for(var index in worldData.enemyList){
            this.addEnemy(worldData.enemyList[index]);
        }

        var playerData:ifPlayerData = getData("PLAYER_DATA");
        this.player.setPosition(playerData.pos.x, playerData.pos.y);
    }

    async addEnemy(data:ifEnemyData){
        if(!data) return;
        var enyPrefab = await GlobalFunction.asyncLoadPrefabEx("prefab/mapObject/enemy", this);
        var enyObj = cc.instantiate(enyPrefab);
        enyObj.setPosition(data.pos.x, data.pos.y);
        enyObj.getComponent("enemyBase").init(data);
        enyObj.getComponent("fllowFunc").setFllowItem(this.player);
        this.objectLayer.addChild(enyObj);
        cc.log("生成一个怪物", data);
    }

    addPlayer(data:ifPlayerData){

    }

    getCamara() :cc.Camera{
        return this.mainCam.getComponent(cc.Camera)
    }

    getPlayer() :cc.Node{
        return this.player;
    }

    getObjectLayer() :cc.Node{
        return this.objectLayer;
    }

    getAttackMode(){
        return this.isAttackMode;
    }

    switchCam(item:cc.Node){
        this.mainCam.getComponent("fllowFunc").setFllowItem(item);
    }

    onClickSwtichCamToPlayer(){
        this.switchCam(this.player);
    }

    onClickSwitchCamToObject(){
        this.switchCam(this.sword);
    }

    onClickAttack(){
        if(this.isAttackMode)
        {
            cc.director.getCollisionManager().enabled = false;
        }
        else
        {
            cc.director.getCollisionManager().enabled = true;
        }
        this.isAttackMode = !this.isAttackMode;
        GlobalEvent.emit(GlobalEvent.Event.swtichAttackMode, this.isAttackMode);
    }

    onClickOpenPanel(){
        GlobalEvent.emit(GlobalEvent.Event.openPanel, {PanelId: ConstData.panelID.playerInfoBox});
    }


}
